<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片列表 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 == 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级权限 -->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 == 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scop">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRightDialog(scop.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRightDialog(scop.row)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scop.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
    <!-- 树形结构 -->
      <el-tree ref="treeRef" :data="rightsList" :props="treeProps" show-checkbox :default-checked-keys="defaultKey" node-key="id" default-expand-all></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑权限的对话框 -->
    <el-dialog title="提示" :visible.sync="editRightDialogVisible" width="50%">
        <!-- 编辑权限的对话框列表 -->
        <div>123</div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="editRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRightDialogVisible = false">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 删除权限对话框 -->
    <el-dialog title="提示" :visible.sync="deleteRightDialogVisible" width="50%">
        <!-- 编辑权限的对话框列表 -->
        <div>123</div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="deleteRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRightDialogVisible = false">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //获取角色权限
      rolesList: [],
      //控制分配权限对话框显示与隐藏
      setRightDialogVisible: false,
      //编辑权限对话框显示与对话框
      editRightDialogVisible: false,
      //删除权限对话框显示与对话框
      deleteRightDialogVisible: false,
      //获取权限列表数据
      rightsList: [],
      //树形空间
      treeProps: {
        label: "authName",
        children: "children",
      },
      //默认选中的权限
      defaultKey: [],
      //当前即将分配权限的id
      roleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取所有角色的列表
    async getRolesList() {
      const { data: result } = await this.$http.get("roles");
      if (result.meta.status !== 200) {
        return this.$Message.error("获取角色列表失败!");
      }
      this.rolesList = result.data;
      console.log(this.rolesList);
    },
    //根据id的删除用户权限
    async removeRightById(role, rightId) {
      //弹框提示用户确认删除
      const confimResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confimResult !== "confirm") {
        return this.$Message.info("已取消删除");
      }
      const { data: result } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (result.meta.status !== 200) {
        return this.$Message.error("删除失败");
      }
      this.$Message.success("删除成功");
      role.children = result.data;
    },
    //修改权限对话框
    async showSetRightDialog(role) {
       this.roleId = role.id
      const { data: result } = await this.$http.get("rights/tree");
      if (result.meta.status !== 200) {
        return this.$Message.error("获取权限列表失败");
      }
      this.rightsList = result.data;
      this.defLeafKeys(role,this.defaultKey)
      this.setRightDialogVisible = true;
    },
    //通过递归的方式，获取角色下所有三级权限id，并保存到defaultKey
    defLeafKeys(node, arr){
        if(!node.children){
            return arr.push(node.id)
        }
        node.children.forEach(element => {
            this.defLeafKeys(element,arr)
        });
    },
    //监听对话框关闭按钮
    setRightDialogClosed(){
        this.defaultKey = []
    },
    async allotRights(){
        const keys = [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
        const idStr = keys.join(',')
        const {data:result} = await this.$http.post(`roles/${this.roleId}/rights`,{
            rids:idStr
        });
        console.log(result)
        if(result.meta.status !== 200){
            return this.$Message.error('权限分配失败')
        }
        this.$Message.success('分配权限成功')
        this.getRolesList()
        this.setRightDialogVisible = false

    },
    //编辑权限对话框
    editRightDialog(role){
        console.log(role)
        this.editRightDialogVisible = true
    },
    //删除权限对话框
    deleteRightDialog(role){
        this.deleteRightDialogVisible = true
    }
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 14px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>